<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WeakMap</title>
</head>
<body>
    <h1>WeakMap</h1>
    <h2>WeakMap只接受对象作为键名，键名是弱引用</h2>

    <script>
        // WeakMap基本用法
        const wm = new WeakMap();
        const element = document.getElementById('example');
        wm.set(element, 'some information');
        console.log(wm.get(element));

        // WeakMap的用途：DOM节点数据
        let myWeakmap = new WeakMap();

        myWeakmap.set(
            document.getElementById('logo'),
            {timesClicked: 0}
        );

        document.getElementById('logo').addEventListener('click', function() {
            let logoData = myWeakmap.get(this);
            logoData.timesClicked++;
        }, false);

        // 典型应用：部署私有属性
        const _counter = new WeakMap();
        const _action = new WeakMap();

        class Countdown {
            constructor(counter, action) {
                _counter.set(this, counter);
                _action.set(this, action);
            }
            dec() {
                let counter = _counter.get(this);
                if (counter < 1) return;
                counter--;
                _counter.set(this, counter);
                if (counter === 0) {
                    _action.get(this)();
                }
            }
        }
    </script>
</body>
</html> 